package org.dtrd.modules.system.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.jeecg.dingtalk.api.core.response.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.dtrd.base.BaseController;
import org.dtrd.common.api.dto.message.MessageDTO;
import org.dtrd.common.api.vo.Result;
import org.dtrd.config.system.SystemState;
import org.dtrd.config.thirdapp.ThirdAppConfig;
import org.dtrd.modules.system.entity.bean.qiyeweixin.QwClientBaseInfo;
import org.dtrd.modules.system.entity.bean.qiyeweixin.QwClientInfoListResponse;
import org.dtrd.modules.system.entity.bean.qiyeweixin.QwClientInfoResponse;
import org.dtrd.modules.system.entity.bean.qiyeweixin.QwGroupInfoRequest;
import org.dtrd.modules.system.service.impl.ThirdAppDingtalkServiceImpl;
import org.dtrd.modules.system.service.impl.ThirdAppWechatEnterpriseServiceImpl;
import org.dtrd.modules.system.vo.thirdapp.SyncInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.dtrd.config.system.SystemState.ResponseState.STATE_PARAMS_MISSING;

/**
 * 第三方App对接
 */
@Slf4j
@RestController("thirdAppController")
@RequestMapping("/sys/thirdApp")
@Api(tags = "第三方APP对接")
public class ThirdAppController extends BaseController {

    @Autowired
    ThirdAppConfig thirdAppConfig;

    @Autowired
    ThirdAppWechatEnterpriseServiceImpl wechatEnterpriseService;

    @Autowired
    ThirdAppDingtalkServiceImpl dingtalkService;

    /**
     * 获取启用的系统
     */
    @GetMapping("/getEnabledType")
    public Result getEnabledType() {
        Map<String, Boolean> enabledMap = new HashMap<>();
        enabledMap.put("wechatEnterprise", thirdAppConfig.isWechatEnterpriseEnabled());
        enabledMap.put("dingtalk", thirdAppConfig.isDingtalkEnabled());
        return Result.OK(enabledMap);
    }

    /**
     * 同步本地[用户]到【企业微信】
     *
     * @param ids
     * @return
     */
    @GetMapping("/sync/wechatEnterprise/user/toApp")
    @ApiOperation("同步本地[用户]到【企业微信】")
    @ApiImplicitParam(paramType = "query", name = "ids", value = "用户id", required = true, dataType = "String")
    public Result syncWechatEnterpriseUserToApp(@RequestParam(value = "ids", required = false) String ids) {
        if (thirdAppConfig.isWechatEnterpriseEnabled()) {
            SyncInfoVo syncInfo = wechatEnterpriseService.syncLocalUserToThirdApp(ids);
            if (syncInfo.getFailInfo().size() == 0) {
                return Result.OK("同步成功", syncInfo);
            } else {
                return Result.error("同步失败", syncInfo);
            }
        }
        return Result.error("企业微信同步功能已禁用");
    }

    /**
     * 同步【企业微信】[用户]到本地
     *
     * @param ids 作废
     * @return
     */
    @GetMapping("/sync/wechatEnterprise/user/toLocal")
    public Result syncWechatEnterpriseUserToLocal(@RequestParam(value = "ids", required = false) String ids) {
        if (thirdAppConfig.isWechatEnterpriseEnabled()) {
            SyncInfoVo syncInfo = wechatEnterpriseService.syncThirdAppUserToLocal();
            if (syncInfo.getFailInfo().size() == 0) {
                return Result.OK("同步成功", syncInfo);
            } else {
                return Result.error("同步失败", syncInfo);
            }
        }
        return Result.error("企业微信同步功能已禁用");
    }

//    /**
//     * 验证企业微信修改用户信息回调
//     *
//     * @return
//     */
//    @GetMapping("/sync/wechatEnterprise/membercallback")
//    public String onWechatEnterpriseMemberCallBackValid(@PathParam("nonce") String nonce, @PathParam("timestamp") String timestamp,
//                                                        @PathParam("msg_signature") String msg_signature, @PathParam("echostr") String echostr) {
//        log.info("ThirdAppController.onWechatEnterpriseUserInfoChanged. nonce=" + nonce + ", timestamp=" + timestamp + ", msg_signature=" + msg_signature + ", echostr" + echostr);
//        if (thirdAppConfig.isWechatEnterpriseEnabled()) {
//            return wechatEnterpriseService.verifyWxUrl(msg_signature, timestamp, nonce, echostr);
////            try {
////                SyncInfoVo syncInfo = wechatEnterpriseService.syncThirdAppUserToLocal();
////                if (syncInfo.getFailInfo().size() == 0) {
////                    return Result.OK("同步成功", syncInfo);
////                } else {
////                    return Result.error("同步失败", syncInfo);
////                }
////            } catch (Exception e) {
//////                e.printStackTrace();
////            }
//        }
//        return "企业微信同步功能已禁用";
//    }
//

    /**
     * 企业微信修改用户信息回调
     *
     * @return
     */
    @PostMapping("/sync/wechatEnterprise/membercallback")
    public Result onWechatEnterpriseUserInfoChanged(@PathParam("nonce") String nonce, @PathParam("timestamp") String timestamp,
                                                    @PathParam("msg_signature") String msg_signature, @RequestBody String postData) {
        log.info("ThirdAppController.onWechatEnterpriseUserInfoChanged. nonce=" + nonce + ", timestamp=" + timestamp + ", msg_signature=" + msg_signature + ", postData" + postData);
        if (thirdAppConfig.isWechatEnterpriseEnabled()) {
            SyncInfoVo syncInfo = wechatEnterpriseService.syncThirdAppUserToLocal();
            if (syncInfo.getFailInfo().size() == 0) {
                return Result.OK("同步成功", syncInfo);
            } else {
                return Result.error("同步失败", syncInfo);
            }
        }
        return Result.error("企业微信同步功能已禁用");
    }

    /**
     * 企业微信的二次认证
     */
    @GetMapping("/wechatEnterprise/auth")
    @ApiOperation("企业微信二次认证")
    @ApiImplicitParam(paramType = "query", name = "code", value = "code", required = true, dataType = "String")
    public Result<?> secondAuth(@PathParam("code") String code) {
        if (StrUtil.isEmpty(code)) {
            return Result.error(STATE_PARAMS_MISSING.getMsg());
        }
        boolean result = wechatEnterpriseService.secondAuth(code);
        return result ? Result.OK("认证成功") : Result.error("认证失败");
    }

    /**
     * 同步本地[部门]到【企业微信】
     *
     * @param ids
     * @return
     */
    @GetMapping("/sync/wechatEnterprise/depart/toApp")
    public Result syncWechatEnterpriseDepartToApp(@RequestParam(value = "ids", required = false) String ids) {
        if (thirdAppConfig.isWechatEnterpriseEnabled()) {
            boolean flag = wechatEnterpriseService.syncLocalDepartmentToThirdApp(ids);
            return flag ? Result.OK("同步成功", null) : Result.error("同步失败");
        }
        return Result.error("企业微信同步功能已禁用");
    }

    /**
     * 同步【企业微信】[部门]到本地
     *
     * @param ids
     * @return
     */
    @GetMapping("/sync/wechatEnterprise/depart/toLocal")
    public Result syncWechatEnterpriseDepartToLocal(@RequestParam(value = "ids", required = false) String ids) {
        if (thirdAppConfig.isWechatEnterpriseEnabled()) {
            SyncInfoVo syncInfo = wechatEnterpriseService.syncThirdAppDepartmentToLocal(ids);
            if (syncInfo.getFailInfo().size() == 0) {
                return Result.OK("同步成功", syncInfo);
            } else {
                return Result.error("同步失败", syncInfo);
            }
        }
        return Result.error("企业微信同步功能已禁用");
    }

    /**
     * 详见企业微信文档
     * https://open.work.weixin.qq.com/api/doc/90000/90135/92571
     *
     * @return
     */
    @ApiOperation("获取配置了客户联系功能的成员列表")
    @GetMapping("/sync/wechatEnterprise/followUserList")
    public Result<?> getFollowUserList() {
        if (thirdAppConfig.isWechatEnterpriseEnabled()) {
            List<String> userList = wechatEnterpriseService.getFollowUserList();
            return Result.OK(userList);
        }
        return Result.error("企业微信功能未开启");
    }

    @ApiOperation("获取客户列表")
    @GetMapping("/sync/wechatEnterprise/clientList")
    public Result<?> getClientList(@PathParam("userId") String userId) {
        if (thirdAppConfig.isWechatEnterpriseEnabled()) {
            List<String> userList = wechatEnterpriseService.getClientList(userId);
            return Result.OK(userList);
        }
        return Result.error("企业微信功能未开启");
    }

    @ApiOperation("获取群聊客户列表")
    @PostMapping("/wechatEnterprise/groupclient")
    public Result<?> getGroupChatClientList(@RequestBody QwGroupInfoRequest request) {
        log.info("ThirdAppController.getGroupChatClientList.[request] request=" + request);
        if (thirdAppConfig.isWechatEnterpriseEnabled()) {
            List<QwClientBaseInfo> userList = wechatEnterpriseService.getGroupClientList(request);
            return Result.OK(userList);
        }
        return Result.error("企业微信功能未开启");
    }

    @ApiOperation("获取客户详情")
    @GetMapping("/sync/wechatEnterprise/clientDetail")
    public Result<?> getClientDetail(@PathParam("clientId") String clientId) {
        if (clientId == null) {
            return Result.error(STATE_PARAMS_MISSING.getMsg());
        }
        if (thirdAppConfig.isWechatEnterpriseEnabled()) {
            QwClientInfoResponse response = wechatEnterpriseService.getClientDetail(clientId);
            return Result.OK(response);
        }
        return Result.error("企业微信功能未开启");
    }

    @ApiOperation("批量获取客户详情")
    @PostMapping("/sync/wechatEnterprise/clientDetail/batch")
    public Result<?> bulkFetchClientDetail(@RequestBody List<String> clientIdList) {
        if (thirdAppConfig.isWechatEnterpriseEnabled()) {
            QwClientInfoListResponse response = wechatEnterpriseService.batchGetClientDetail(clientIdList);
            return Result.OK(response);
        }
        return Result.error("企业微信功能未开启");
    }

    @ApiOperation("企业微信回调")
    @PostMapping("/sync/wechatEnterprise/callback")
    public String onQiyeWxCallBack(@PathParam("nonce") String nonce, @PathParam("timestamp") String timestamp,
                                   @PathParam("msg_signature") String msg_signature, @RequestBody String postData) {
        log.info("ThirdAppController.getApi.[request, nonce = " + nonce + ", timestamp=" + timestamp + ", signature=" + msg_signature);
        log.info("ThirdAppController.onQiyeWxCallBack.[request, nonce, timestamp, msg_signature, postData = " + postData);
        return wechatEnterpriseService.onQiyeWxCallBack(msg_signature, timestamp, nonce, postData);
    }

    @ApiOperation("验证企业微信回调")
    @GetMapping("/sync/wechatEnterprise/callback")
    public String validWxCallback(@PathParam("nonce") String nonce, @PathParam("timestamp") String timestamp,
                                  @PathParam("msg_signature") String msg_signature, @PathParam("echostr") String echostr) {
        log.info("ThirdAppController.va.[nonce = " + nonce + ", timestamp=" + timestamp + ", signature=" + msg_signature + ", echostr=" + echostr);
        return wechatEnterpriseService.verifyWxUrl(msg_signature, timestamp, nonce, echostr);
    }

    @ApiOperation("根据企微id获取系统用户id")
    @GetMapping("/wechatEnterprise/login")
    public Result<?> qwLogin(@PathParam("userId") String userId) {
        if (userId == null) {
            return error(STATE_PARAMS_MISSING);
        }
        Integer patientId = wechatEnterpriseService.getPatientIdByQwUserId(userId);
        if (patientId == null) {
            return error(SystemState.ResponseState.STATE_PARAMS_ERROR);
        }
        return Result.OK(patientId);
    }

    /**
     * 同步本地[部门]到【钉钉】
     *
     * @param ids
     * @return
     */
    @GetMapping("/sync/dingtalk/depart/toApp")

    public Result syncDingtalkDepartToApp(@RequestParam(value = "ids", required = false) String ids) {
        if (thirdAppConfig.isDingtalkEnabled()) {
            boolean flag = dingtalkService.syncLocalDepartmentToThirdApp(ids);
            return flag ? Result.OK("同步成功", null) : Result.error("同步失败");
        }
        return Result.error("钉钉同步功能已禁用");
    }

    /**
     * 同步【钉钉】[部门]到本地
     *
     * @param ids
     * @return
     */
    @GetMapping("/sync/dingtalk/depart/toLocal")
    public Result syncDingtalkDepartToLocal(@RequestParam(value = "ids", required = false) String ids) {
        if (thirdAppConfig.isDingtalkEnabled()) {
            SyncInfoVo syncInfo = dingtalkService.syncThirdAppDepartmentToLocal(ids);
            if (syncInfo.getFailInfo().size() == 0) {
                return Result.OK("同步成功", syncInfo);
            } else {
                return Result.error("同步失败", syncInfo);
            }
        }
        return Result.error("钉钉同步功能已禁用");
    }

    /**
     * 同步本地[用户]到【钉钉】
     *
     * @param ids
     * @return
     */
    @GetMapping("/sync/dingtalk/user/toApp")
    public Result syncDingtalkUserToApp(@RequestParam(value = "ids", required = false) String ids) {
        if (thirdAppConfig.isDingtalkEnabled()) {
            SyncInfoVo syncInfo = dingtalkService.syncLocalUserToThirdApp(ids);
            if (syncInfo.getFailInfo().size() == 0) {
                return Result.OK("同步成功", syncInfo);
            } else {
                return Result.error("同步失败", syncInfo);
            }
        }
        return Result.error("钉钉同步功能已禁用");
    }

    /**
     * 同步【钉钉】[用户]到本地
     *
     * @param ids 作废
     * @return
     */
    @GetMapping("/sync/dingtalk/user/toLocal")
    public Result syncDingtalkUserToLocal(@RequestParam(value = "ids", required = false) String ids) {
        if (thirdAppConfig.isDingtalkEnabled()) {
            SyncInfoVo syncInfo = dingtalkService.syncThirdAppUserToLocal();
            if (syncInfo.getFailInfo().size() == 0) {
                return Result.OK("同步成功", syncInfo);
            } else {
                return Result.error("同步失败", syncInfo);
            }
        }
        return Result.error("钉钉同步功能已禁用");
    }

    /**
     * 发送消息测试
     *
     * @return
     */
    @PostMapping("/sendMessageTest")
    public Result sendMessageTest(@RequestBody JSONObject params, HttpServletRequest request) {
        /* 获取前台传递的参数 */
        // 第三方app的类型
        String app = params.getString("app");
        // 是否发送给全部人
        boolean sendAll = params.getBooleanValue("sendAll");
        // 消息接收者，传sys_user表的username字段，多个用逗号分割
        String receiver = params.getString("receiver");
        // 消息内容
        String content = params.getString("content");

//        String fromUser = JwtUtil.getUserNameByToken(request);
        String fromUser = "Test";
        String title = "第三方APP消息测试";
        MessageDTO message = new MessageDTO(fromUser, receiver, title, content);
        message.setToAll(sendAll);

        if (ThirdAppConfig.WECHAT_ENTERPRISE.equals(app)) {
            if (thirdAppConfig.isWechatEnterpriseEnabled()) {
                JSONObject response = wechatEnterpriseService.sendMessageResponse(message, false);
                return Result.OK(response);
            }
            return Result.error("企业微信已被禁用");
        } else if (ThirdAppConfig.DINGTALK.equals(app)) {
            if (thirdAppConfig.isDingtalkEnabled()) {
                Response<String> response = dingtalkService.sendMessageResponse(message, false);
                return Result.OK(response);
            }
            return Result.error("钉钉已被禁用");
        }
        return Result.error("不识别的第三方APP");
    }

    /**
     * 撤回消息测试
     *
     * @return
     */
    @PostMapping("/recallMessageTest")
    public Result recallMessageTest(@RequestBody JSONObject params) {
        /* 获取前台传递的参数 */
        // 第三方app的类型
        String app = params.getString("app");
        // 消息id
        String msg_task_id = params.getString("msg_task_id");

        if (ThirdAppConfig.WECHAT_ENTERPRISE.equals(app)) {
            if (thirdAppConfig.isWechatEnterpriseEnabled()) {
                return Result.error("企业微信不支持撤回消息");
            }
            return Result.error("企业微信已被禁用");
        } else if (ThirdAppConfig.DINGTALK.equals(app)) {
            if (thirdAppConfig.isDingtalkEnabled()) {
                Response<JSONObject> response = dingtalkService.recallMessageResponse(msg_task_id);
                if (response.isSuccess()) {
                    return Result.OK("撤回成功", response);
                } else {
                    return Result.error("撤回失败：" + response.getErrcode() + "——" + response.getErrmsg(), response);
                }
            }
            return Result.error("钉钉已被禁用");
        }
        return Result.error("不识别的第三方APP");
    }

    @ApiOperation("华为数据回调")
    @PostMapping("/huawei/callback")
    public Result<?> getApi(@RequestBody JSONObject object) {
        log.info("ThirdAppController.getApi.[object = {}", object);
        // TODO 待实现
        return Result.OK("success");
    }

}
